package com.sta.oldman.coder;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class IntegratedTcpMsgSender {
    // 目标 HTTP 接口地址
    private static final String API_URL = "http://127.0.0.1:8081/message/send";
    // 发送间隔 (毫秒)
    private static final long SEND_INTERVAL = 1000;
    // Gson 实例用于 JSON 序列化
    private static final Gson gson = new Gson();
    // 存储解析后的消息列表
    private static List<TcpMsg> tcpMsgList = new ArrayList<>();
    // 消息发送索引
    private static int currentIndex = 0;

    public static void main(String[] args) {
// 1. 解析十六进制字符串生成 TcpMsg 列表
        parseTcpMsgsFromHexString();

// 2. 启动定时发送任务
        startScheduledSender();
    }

    /**

     从十六进制字符串解析生成 TcpMsg 列表
     */
    private static void parseTcpMsgsFromHexString() {
        String msg = "53 59 80 03 01 01 31 54 43 53 59 80 04 02 0B 3D 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 05 09 C5 54 43 53 59 80 03 01 01 31 54 43 53 59 80 04 02 0B 3D 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 05 09 C5 54 43 53 59 80 03 01 01 31 54 43 53 59 80 04 02 0B 3D 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 05 09 C5 54 43 53 59 80 03 01 01 31 54 43 53 59 80 04 02 17 49 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 13 0B D5 54 43 53 59 80 03 01 01 31 54 43 53 59 80 04 02 17 49 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 13 0B D5 54 43 53 59 80 03 01 01 31 54 43 53 59 80 04 02 17 49 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 13 0B D5 54 43 53 59 80 03 01 01 31 54 43 53 59 80 04 02 23 55 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 1D 13 E7 54 43 53 59 80 03 01 01 31 54 43 53 59 80 04 02 23 55 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 1D 13 E7 54 43 53 59 80 03 01 01 31 54 43 53 59 80 04 02 23 55 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 1D 13 E7 54 43 53 59 80 03 01 01 31 54 43 53 59 80 04 02 23 55 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 05 09 C5 54 43 53 59 80 03 01 01 31 54 43 53 59 80 04 02 0B 3D 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 05 09 C5 54 43 53 59 80 03 01 01 31 54 43 53 59 80 04 02 0B 3D 54 43 53 59 80 03 01 01 31 54 43 53 59 80 05 06 80 05 09 C5 54 43";
        String[] hexBytes = msg.split(" ");
        int index = 0;
// 解析十六进制字符串为 TcpMsg 列表
        while (index + 8 < hexBytes.length) {
// 验证消息头 (0x5359)
            if (!"53".equals(hexBytes[index]) || !"59".equals(hexBytes[index + 1])) {
                index++;
                continue;
            }
// 提取控制字段和命令字段
            byte control = (byte) Integer.parseInt(hexBytes[index + 2], 16);
            byte command = (byte) Integer.parseInt(hexBytes[index + 3], 16);
            short length = (short) Integer.parseInt(hexBytes[index + 4], 16);
// 验证数据长度是否足够
            if (index + 5 + length + 2 > hexBytes.length) {
                break;
            }
// 提取数据部分
            byte[] data = new byte[length];
            for (int i = 0; i < length; i++) {
                data[i] = (byte) Integer.parseInt(hexBytes[index + 5 + i], 16);
            }
// 计算校验和 (与 Client 原逻辑保持一致)
            int sum = 0x5359; // 头部参与校验
            sum += control & 0xFF;
            sum += command & 0xFF;
            sum += length & 0xFFFF;
            for (byte b : data) {
                sum += b & 0xFF;
            }
            byte checksum = (byte) (sum & 0xFF);
// 验证消息尾 (0x5443)
            if (!"54".equals(hexBytes[index + 6 + length]) || !"43".equals(hexBytes[index + 7 + length])) {
                index++;
                continue;
            }
// 创建 TcpMsg 对象并添加到列表
            TcpMsg tcpMsg = new TcpMsg(control, command, length, data, checksum);
            tcpMsgList.add(tcpMsg);
// 移动到下一个消息起始位置
            index += 8 + length;
        }
        System.out.println("解析完成，共生成" + tcpMsgList.size() + "条消息");
    }

    /**

     启动定时发送任务
     */
    private static void startScheduledSender() {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// 定时发送任务：延迟 0 秒开始，每隔指定间隔发送一次
        executor.scheduleAtFixedRate(() -> {
            if (tcpMsgList.isEmpty()) {
                System.out.println("没有可发送的消息");
                return;
            }
// 循环获取消息（发送完列表后重新开始）
            TcpMsg currentMsg = tcpMsgList.get(currentIndex);
            currentIndex = (currentIndex + 1) % tcpMsgList.size();
// 发送消息到 HTTP 接口
            sendTcpMsgToHttp(currentMsg);
        }, 0, SEND_INTERVAL, TimeUnit.MILLISECONDS);
    }

    /**

     发送 TcpMsg 到 HTTP 接口
     */
    private static void sendTcpMsgToHttp(TcpMsg tcpMsg) {
        try {
            URL url = new URL(API_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置 HTTP 请求参数
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);
// 序列化 TcpMsg 为 JSON
            String jsonBody = gson.toJson(tcpMsg);
// 发送请求
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
// 处理响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应内容
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    System.out.printf("发送成功 [index=% d, control=0x%02X, command=0x%02X] 响应: % s% n",
                            currentIndex, tcpMsg.getControl() & 0xFF, tcpMsg.getCommand() & 0xFF, response.toString());
                }
            } else {
                System.err.printf("发送失败 [index=% d] 状态码: % d% n", currentIndex, responseCode);
            }
        } catch (IOException e) {
            System.err.printf("发送异常 [index=% d]: % s% n", currentIndex, e.getMessage());
        }
    }
}